<template>
  <div class="app-container">

    <el-container>
      <el-header class="filter-header">
        <div class="filter-container">
          <!-- 第一行：状态筛选 + 时间范围 -->
          <div class="filter-row">
            <div class="filter-group">
              <label class="filter-label">状态</label>
              <el-popover
                v-model="stateTreeVisible"
                placement="bottom-start"
                width="320"
                trigger="click"
                popper-class="state-tree-popover"
              >
                <div class="state-tree-container">
                  <div class="state-tree-header">
                    <!-- 快捷分组选择 -->
                    <div class="quick-groups-section">
                      <div class="quick-groups-controls">
                        <el-select
                          v-model="selectedGroupId"
                          placeholder="选择预设分组"
                          size="mini"
                          clearable
                          class="groups-select"
                          @change="handleApplyGroup"
                        >
                          <el-option
                            v-for="group in stateGroups"
                            :key="group.id"
                            :label="group.name"
                            :value="group.id"
                          >
                            <span class="group-color-indicator" :style="{ backgroundColor: group.color }" />
                            <span>{{ group.name }}</span>
                          </el-option>
                        </el-select>
                        <el-button
                          icon="el-icon-setting"
                          size="mini"
                          circle
                          title="管理分组"
                          class="groups-manage-btn"
                          @click="showGroupManager = true"
                        />
                      </div>
                    </div>

                    <!-- 操作按钮 -->
                    <div class="state-tree-actions">
                      <el-button size="mini" type="text" @click="handleSelectAllStates">全选</el-button>
                      <el-button size="mini" type="text" @click="handleClearAllStates">清空</el-button>
                    </div>
                  </div>
                  <el-tree
                    ref="stateTree"
                    :data="stateTreeData"
                    :props="stateTreeProps"
                    show-checkbox
                    node-key="id"
                    :check-strictly="true"
                    :default-expanded-keys="expandedStateKeys"
                    class="state-tree"
                    @check-change="handleStateTreeCheck"
                  >
                    <span slot-scope="{ node, data }" class="state-tree-node">
                      <span class="state-color-indicator" :style="{ backgroundColor: data.color || '#409eff' }" />
                      <span class="state-name">{{ node.label }}</span>
                    </span>
                  </el-tree>
                </div>
                <el-button
                  slot="reference"
                  size="small"
                  style="width: 200px"
                  class="state-selector-btn"
                >
                  <span v-if="selectedStateNames.length === 0" class="placeholder-text">请选择状态</span>
                  <span v-else-if="selectedStateNames.length === 1" class="selected-text">{{ selectedStateNames[0] }}</span>
                  <span v-else class="selected-text">已选择 {{ selectedStateNames.length }} 个状态</span>
                  <i class="el-icon-arrow-down el-icon--right" />
                </el-button>
              </el-popover>
            </div>

            <div class="filter-group">
              <label class="filter-label">时间范围</label>
              <el-date-picker
                v-model="dateRange"
                type="daterange"
                size="small"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :picker-options="pickerOptions"
                format="yyyy-MM-dd"
                value-format="timestamp"
                style="width: 400px"
                @change="handleDateRangeChange"
              />
            </div>
          </div>

          <!-- 第二行：搜索框 + 新增按钮 -->
          <div class="filter-row">
            <div class="filter-group">
              <label class="filter-label">关键词</label>
              <el-input
                v-model="kwInput"
                placeholder="输入订单名称编号或者客户名称邮箱进行搜索"
                size="small"
                clearable
                style="width: 400px"
                @keyup.native.enter="handleSearch"
              >
                <el-button slot="append" icon="el-icon-search" :loading="listLoading" @click="handleSearch">搜索</el-button>
              </el-input>
            </div>

            <div class="filter-actions">
              <el-button
                type="success"
                size="small"
                icon="el-icon-plus"
                @click="handleCreateOrder"
              >新增订单</el-button>
            </div>
          </div>
        </div>
      </el-header>
      <el-main style="overflow-x: auto; width: 100%;">
        <el-table
          v-loading="listLoading"
          :data="data"
          border
          fit
          highlight-current-row
          stripe
          :default-sort="{prop: 'create_at', order: 'descending'}"
          :row-style="tableRowStyle"
          :cell-style="cellStyle"
          style="width: 100%; border-color: #d0d7de;"
          :header-cell-style="headerCellStyle"
          @sort-change="handleSort"
        >
          <el-table-column align="left" label="编号" width="120" prop="order_no" sortable="custom">
            <template slot-scope="scope">
              <span @click="hanldeModifyOrderState(scope.row)">{{ scope.row.order_no }}</span>
              <el-button type="text" icon="el-icon-document-copy" @click="hanldeCopyLink(scope.row)" />
            </template>
          </el-table-column>

          <el-table-column align="left" label="订单信息" min-width="300" prop="name" sortable="custom">
            <template slot-scope="scope">
              <div style="margin-bottom: 8px;">
                <span style="font-weight: bold; color: #303133;" @click="hanldeModifyOrderState(scope.row)">{{ scope.row.name }}</span>
                <el-tag effect="dark" size="mini" :color="scope.row.crmorderstate__color" style="margin-left: 8px;" @click="hanldeModifyOrderState(scope.row)">{{ scope.row.crmorderstate__name }}</el-tag>
              </div>
              <div v-if="scope.row.remender" style="background: #fff2e8; border: 1px solid #f7ba2a; border-radius: 4px; padding: 6px 10px; margin-top: 6px;">
                <el-icon class="el-icon-warning" style="color: #e6a23c; margin-right: 4px;" />
                <span v-if="scope.row.remender === '请审核'" style="color: #e6a23c; font-weight: 500;">{{ scope.row.remender }}</span>
                <span v-else style="color: #e6a23c; font-weight: 500;">{{ scope.row.remender }}</span>
              </div>
            </template>
          </el-table-column>

          <el-table-column align="center" label="优先级" width="140" prop="star" sortable="custom">
            <template slot-scope="scope">
              <el-rate v-model="scope.row.star" @change="handleSetOrderField('star', scope.row)" />
            </template>
          </el-table-column>

          <el-table-column align="left" label="客户信息" width="280" prop="customer.name" sortable="custom">
            <template slot-scope="scope">
              <div style="display: flex; align-items: center; margin-bottom: 4px;">
                <svg-icon :icon-class="scope.row.customer.country" style="margin-right: 6px;" />
                <el-popover
                  placement="top-start"
                  width="400"
                  trigger="click"
                >
                  <el-card class="box-card">
                    <div slot="header" class="clearfix">
                      <span>{{ scope.row.customer.name }}</span>
                    </div>
                    <div>
                      <p><strong>公司：</strong>{{ scope.row.customer.company }}</p>
                      <p><strong>域名：</strong>{{ scope.row.customer.domain }}</p>
                      <p><strong>邮箱：</strong>{{ scope.row.customer.mail }}</p>
                      <p><strong>电话：</strong>{{ scope.row.customer.phone }}</p>
                      <p><strong>WhatsApp：</strong>{{ scope.row.customer.whatsapp }}</p>
                      <p><strong>国家：</strong><span v-if="scope.row.customer.country"><svg-icon :icon-class="scope.row.customer.country" />{{ getCountryLabel(scope.row.customer.country) }}</span></p>
                      <p><strong>来源：</strong>{{ scope.row.customer.source }}</p>
                    </div>
                  </el-card>
                  <span slot="reference" style="cursor: pointer; color: #409eff;">{{ scope.row.customer.name }}</span>
                </el-popover>
                <el-tag v-if="scope.row.customer.crmcustomercategory_id !== ''" type="success" effect="dark" size="mini" style="margin-left: 6px;">{{ scope.row.customer.crmcustomercategory__name }}</el-tag>
              </div>
              <div v-if="scope.row.customer.tag && scope.row.customer.tag.length > 0">
                <el-tag v-for="(item, index) in scope.row.customer.tag" :key="index" effect="plain" size="mini" style="margin-right: 4px; margin-top: 2px;">{{ item }}</el-tag>
              </div>
            </template>
          </el-table-column>

          <el-table-column align="left" label="时间信息" width="180" prop="mailbox_data" sortable="custom">
            <template slot-scope="scope">
              <div style="margin-bottom: 4px;">
                <span style="font-size: 12px; color: #909399;">最后沟通：</span>
                <span style="cursor: pointer; color: #409eff; font-size: 12px; min-width: 60px; display: inline-block;" @click="handleEditMail(scope.row)">{{ scope.row.last_chat_at || '无' }}</span>
                <el-button icon="el-icon-edit" size="mini" type="text" style="padding: 0; margin-left: 4px;" @click="handleEditMail(scope.row)" />
              </div>
              <div>
                <span style="font-size: 12px; color: #909399;">创建时间：{{ scope.row.create_at.split(' ')[0] }}</span>
              </div>
            </template>
          </el-table-column>

          <el-table-column align="left" label="处理人" width="160" prop="creator" sortable="custom">
            <template slot-scope="scope">
              <div style="margin-bottom: 4px;">
                <span style="font-size: 12px; color: #909399;">当前：</span>
                <span style="font-size: 12px;">{{ scope.row.manager }}</span>
              </div>
              <el-select
                v-model="scope.row.manager_id"
                placeholder="指定处理人"
                size="mini"
                filterable
                clearable
                @change="handleChangeManager(scope.row)"
              >
                <el-option
                  v-for="user in users"
                  :key="user.id"
                  :label="user.show_name"
                  :value="user.id"
                />
              </el-select>
            </template>
          </el-table-column>

          <el-table-column align="center" label="操作" fixed="right" width="120">
            <template slot-scope="scope">
              <el-button
                size="mini"
                icon="el-icon-edit"
                type="primary"
                plain
                @click="hanldeModifyOrderState(scope.row)"
              >编辑
              </el-button>
              <el-button
                v-if="$store.getters.roles.indexOf('sales_manager') !== -1"
                size="mini"
                icon="el-icon-delete"
                type="danger"
                plain
                @click="handleDeleteOrder(scope.row)"
              >删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          v-if="data.length"
          background
          class="mt-pagination"
          :current-page="page"
          :page-sizes="[10,20,50,100]"
          :page-size="pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </el-main>
      <crmorderdetail :order_data="current_order" :order-states="parentOrderStats" :show-able="modifyOrderStateVisible" @close="modifyOrderStateVisible=false" />
      <crmsendmail :mailbox_data="mailbox_data" :is-visible="editMailVisible" @close="editMailVisible=false;" />

      <!-- 状态分组管理对话框 -->
      <el-dialog
        title="状态分组管理"
        :visible.sync="showGroupManager"
        width="900px"
        :before-close="handleCloseGroupManager"
      >
        <!-- 分组列表 -->
        <div style="margin-bottom: 20px;">
          <el-button type="primary" size="small" @click="showGroupForm = true">
            新增分组
          </el-button>
        </div>

        <el-table v-loading="groupsLoading" :data="stateGroups" class="group-table" stripe>
          <el-table-column prop="name" label="分组名称" width="150" />
          <el-table-column prop="description" label="描述" width="200" />
          <el-table-column label="包含状态" min-width="300">
            <template slot-scope="scope">
              <el-tag
                v-for="state in scope.row.state_details"
                :key="state.id"
                :color="state.color"
                effect="dark"
                size="mini"
                class="state-tag"
              >
                {{ state.name }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="分组颜色" width="100" align="center">
            <template slot-scope="scope">
              <span
                :style="{
                  backgroundColor: scope.row.color,
                  color: 'white',
                  padding: '2px 8px',
                  borderRadius: '3px',
                  fontSize: '12px'
                }"
              >
                {{ scope.row.color }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120" align="center">
            <template slot-scope="scope">
              <el-button size="mini" @click="editGroup(scope.row)">编辑</el-button>
              <el-button size="mini" type="danger" @click="deleteGroup(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 新增/编辑分组表单 -->
        <el-dialog
          :title="editingGroupId ? '编辑分组' : '新增分组'"
          :visible.sync="showGroupForm"
          width="600px"
          append-to-body
          class="group-form-dialog"
        >
          <el-form ref="groupFormRef" :model="groupForm" label-width="100px">
            <el-form-item label="分组名称" prop="name" :rules="[{ required: true, message: '请输入分组名称' }]">
              <el-input v-model="groupForm.name" placeholder="请输入分组名称" />
            </el-form-item>

            <el-form-item label="选择状态" prop="states" :rules="[{ required: true, message: '请选择至少一个状态' }]">
              <el-cascader
                v-model="groupForm.states"
                :options="orderStates"
                :props="{ checkStrictly: true, value: 'id', label: 'name', multiple: true }"
                clearable
                collapse-tags
                placeholder="请选择状态"
                style="width: 100%"
              />
            </el-form-item>

            <el-form-item label="分组颜色">
              <el-color-picker v-model="groupForm.color" />
            </el-form-item>

            <el-form-item label="描述">
              <el-input
                v-model="groupForm.description"
                type="textarea"
                placeholder="请输入分组描述"
                :rows="3"
              />
            </el-form-item>

            <el-form-item label="默认分组">
              <el-switch v-model="groupForm.is_default" />
            </el-form-item>
          </el-form>

          <div slot="footer">
            <el-button @click="resetGroupForm">取消</el-button>
            <el-button :loading="saveLoading" type="primary" @click="saveGroup">
              {{ editingGroupId ? '更新' : '创建' }}
            </el-button>
          </div>
        </el-dialog>
      </el-dialog>
    </el-container>
  </div>
</template>

<script>
import { Get, Delete, Put as PutOrder, CrmOrderNotice } from '@/api/crm/crmorder'
import { Get as GetOrderStatus } from '@/api/crm/crmorderstate'
import { GetStateGroups, CreateStateGroup, UpdateStateGroup, DeleteStateGroup, ApplyStateGroup } from '@/api/crm/crmorderstategroup'
import qs from 'qs'
import Crmorderdetail from './elements/crmorderdetail'
import { getCountryLabel, countries } from '../../api/crm/crmcommon'
import Crmsendmail from './elements/crmsendmail'
import { CRMGetProjectUsers as GetUsers } from '@/api/crm/crmmanage'

const orderMapper = {
  'ascending': 0,
  'descending': 1,
  'null': ''
}

export default {
  components: { Crmsendmail, Crmorderdetail },
  data() {
    return {
      users: [],
      ownersLoading: false,
      mailbox_data: '',
      editMailVisible: false,
      getCountryLabel: getCountryLabel,
      countries: countries,
      title: '新增配置',
      state: '',
      orderstatesloading: false,
      orderStates: [],
      cascaderValue: [],
      parentOrderStats: [],
      // 树形状态筛选相关
      stateTreeVisible: false,
      stateTreeData: [],
      stateTreeProps: {
        children: 'children',
        label: 'name',
        disabled: 'disabled'
      },
      expandedStateKeys: [],
      selectedStateNames: [],
      dialogVisible: false,
      temp: {
        id: '',
        name: '',
        order_no: '',
        trade_type: '',
        invoice_number: '',
        crmorderstate_id: '',
        currency: 'USD'
      },
      wp_account_id: '',
      projectsLoading: false,
      webs: [],
      kwInput: '',
      keyword: '',
      data: [],
      listLoading: false,
      showpage_visible: false,
      showLPNdeVisible: false,
      action: '',
      order_by: '',
      order_desc: '',
      // pagination
      pagesize: 10,
      page: 1,
      total: 0,
      base_view_url: '',
      modifyOrderStateVisible: false,
      current_order: {
        name: ''
      },
      dateRange: [],
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            picker.$emit('pick', [start, end])
          }
        }]
      },
      // 状态分组相关
      stateGroups: [],
      selectedGroupId: null,
      showGroupManager: false,
      showGroupForm: false,
      groupsLoading: false,
      saveLoading: false,
      editingGroupId: null,
      groupForm: {
        name: '',
        states: [],
        color: '#409EFF',
        description: '',
        is_default: false
      }
    }
  },
  watch: {
    '$route'(to, from) {
      // 监听路由变化，如果state参数改变，重新设置状态过滤
      if (to.query.state !== from.query.state) {
        this.state = to.query.state || ''
        if (this.state && this.orderStates.length > 0) {
          // 更新树形选择器的值
          this.setTreeValueByStateIds(this.state)
          this.getList()
        } else {
          this.cascaderValue = []
          this.selectedStateNames = []
          if (this.$refs.stateTree) {
            this.$refs.stateTree.setCheckedKeys([])
          }
          this.getList()
        }
      }
      // 监听关键词变化
      if (to.query.kw !== from.query.kw) {
        this.kwInput = to.query.kw || ''
        this.getList()
      }
    }
  },
  created() {
    this.handleFetchGetUsers()
    this.base_view_url = process.env.VUE_APP_BASE_API + '/cms/api/view_html/?'
    // 获取url参数
    this.kwInput = this.$route.query.kw || ''
    this.state = this.$route.query.state || ''

    // 先获取订单状态，然后再加载数据
    this.handleGetOrderState().then(() => {
      this.getList()
      // 加载状态分组
      this.loadStateGroups()
    }).catch(() => {
      this.getList()
      // 加载状态分组
      this.loadStateGroups()
    })
  },
  methods: {
    tableRowStyle() {
      return {
        height: '60px'
      }
    },
    cellStyle({ row, column, rowIndex, columnIndex }) {
      return {
        'border-bottom': '2px solid #d0d7de',
        'border-right': '1px solid #d0d7de'
      }
    },
    headerCellStyle({ row, column, rowIndex, columnIndex }) {
      return {
        'background-color': '#f8f9fa',
        'color': '#606266',
        'font-weight': '600',
        'border-bottom': '2px solid #d0d7de',
        'border-right': '1px solid #d0d7de'
      }
    },
    handleChangeManager(row) {
      CrmOrderNotice({ manager_id: row.manager_id, crmorder_id: row.id }).then((response) => {
        this.notify('发送成功')
      })
    },
    handleFetchGetUsers() {
      this.ownersLoading = true
      GetUsers(null, qs.stringify({ 'is_active': 1 }))
        .then(response => {
          this.ownersLoading = false
          this.users = response.data.data
        })
        .catch(e => {
          this.ownersLoading = false
        })
    },
    hanldeCopyLink(row) {
      const currentUrl = new URL(window.location.href)
      // 删除已存在参数数
      const link = currentUrl.toString().split('?')[0] + '?kw=' + row.order_no

      const orderInfo = `订单编号：${row.order_no}
    客户国家：${this.getCountryLabel(row.customer.country)}
    订单名称：${row.name}
    订单需求：${row.quote || '未提供'}
    订单创建时间：${row.create_at}
    订单链接：${link}`

      this.$copyText(orderInfo).then(() => {
        this.notify('订单信息复制成功')
      }).catch(err => {
        console.error('Failed to copy: ', err)
        this.notify('复制失败', 'error')
      })
    },
    hanldeModifyOrderState(row) {
      this.modifyOrderStateVisible = true
      // 使用深拷贝创建新的对象引用，确保子组件能够检测到变化
      this.current_order = JSON.parse(JSON.stringify(row))
    },
    resetTemp() {
      this.temp = {
        wpaccount_id: '',
        project_id: '',
        name: '',
        url: '',
        source_code: ''
      }
    },
    handleEditMail(row) {
      if (row.mailbox_data) {
        this.mailbox_data = row.mailbox_data
      } else {
        this.mailbox_data = {
          mail_date: '',
          mail_date_short: '',
          mail_date_in_day: '',
          crmcustomer_id: row.crmcustomer_id,
          mail_to: row.customer.mail,
          mail_from: row.customer.mail,
          subject: '',
          short_content: '',
          readed: false
        }
      }
      this.editMailVisible = true
      console.log('editMailVisible set to:', this.editMailVisible)
    },
    handleSetOrderField(field_name, row) {
      // 使用row[field_name]获取属性值
      const updateData = { [field_name]: row[field_name] }

      PutOrder(row.id, updateData).then((response) => {
        // 使用Element UI的通知方法来提示成功消息
        console.log('modify success')
      })
    },
    handleGrabOrder(row) {
      this.$confirm('此操作将抢单, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        PutOrder(row.id, { grab: '1' }).then((response) => {
          row.manager = response.data.manager
          this.notify('抢单成功')
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消抢单'
          })
        })
      })
    },
    handleDeleteOrder(row) {
      this.$confirm('此操作将永久删除订单以及订单相关数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        Delete(row.id).then((response) => {
          this.dialogVisible = false
          this.getList()
          this.notify('删除成功')
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    filterMethod(query, item) {
      return item.domain.indexOf(query) > -1
    },
    handleAddNew() {
      this.crawlkeywordDialogVisible = true
    },
    notify(message, duration) {
      this.$notify({
        title: '成功',
        message: message,
        type: 'success',
        duration: duration || 2000
      })
    },
    getList() {
      this.listLoading = true
      Get(null, qs.stringify({
        kw: this.kwInput,
        pagesize: this.pagesize,
        project_id: this.$store.getters.projectId,
        page: this.page,
        order_by: this.order_by,
        state: this.state,
        order_desc: this.order_desc,
        start_date: this.dateRange ? this.dateRange[0] : '',
        end_date: this.dateRange ? this.dateRange[1] : ''
      }))
        .then(response => {
          this.scrollTop()
          this.data = response.data.data
          this.listLoading = false
          this.total = response.data.total
        }).catch(e => {
          this.listLoading = false
        })
    },
    // pageSize 改变后触发 table 更新
    handleSizeChange(val) {
      this.pagesize = val
      this.getList()
    },
    // page 改变后触发 table 更新
    handlePageChange(val) {
      this.page = val
      this.getList()
    },
    // 点击搜索
    handleSearch() {
      this.page = 1
      this.getList()
    },
    handleSort(v) {
      this.order_by = v.prop
      this.order_desc = orderMapper[v.order]
      this.getList()
    },
    handleChangeState(value) {
      // 支持多选，获取所有选中的最后一级ID
      this.state = value.map(v => Array.isArray(v) ? v[v.length - 1] : v).filter(Boolean).join(',')
      // 调用 getList 方法
      this.getList()
    },
    // 树形状态筛选相关方法
    handleSelectAllStates() {
      // 获取所有节点的key
      const allKeys = this.getAllStateKeys(this.stateTreeData)
      this.$refs.stateTree.setCheckedKeys(allKeys)
      this.updateSelectedStates()
    },
    handleClearAllStates() {
      this.$refs.stateTree.setCheckedKeys([])
      this.updateSelectedStates()
    },
    getAllStateKeys(data) {
      let keys = []
      data.forEach(item => {
        keys.push(item.id)
        if (item.children && item.children.length > 0) {
          keys = keys.concat(this.getAllStateKeys(item.children))
        }
      })
      return keys
    },
    handleStateTreeCheck() {
      this.updateSelectedStates()
    },
    updateSelectedStates() {
      const checkedKeys = this.$refs.stateTree.getCheckedKeys()
      const checkedNodes = this.$refs.stateTree.getCheckedNodes()

      // 更新状态ID字符串
      this.state = checkedKeys.join(',')

      // 更新选中的状态名称
      this.selectedStateNames = checkedNodes.map(node => node.name)

      // 调用列表更新
      this.getList()
    },
    handleDateRangeChange(val) {
      this.getList()
    },
    findStatePath(states, targetId, path = []) {
      // 递归查找状态路径
      for (const state of states) {
        const currentPath = [...path, state.id]
        // 转换为字符串比较，支持数字和字符串类型
        if (String(state.id) === String(targetId)) {
          return currentPath
        }
        if (state.children && state.children.length > 0) {
          const childPath = this.findStatePath(state.children, targetId, currentPath)
          if (childPath) {
            return childPath
          }
        }
      }
      return null
    },
    setCascaderValueByStateId(stateId) {
      const statePath = this.findStatePath(this.orderStates, stateId)
      if (statePath) {
        this.cascaderValue = [statePath]
        console.log('设置级联选择器值:', statePath)
      } else {
        console.log('未找到状态路径:', stateId)
      }
    },
    scrollTop() {
      window.scrollTo(0, 0)
    },
    handleCreateOrder() {
      const link = this.$router.resolve({ name: 'crmcreateorder' })
      window.open(link.href, '_blank')
    },
    handleGetOrderState() {
      this.orderstatesloading = true
      return GetOrderStatus(null, qs.stringify({
        pagesize: 500,
        all: '1',
        page: 1,
        order_by: 'index',
        order_desc: this.order_desc
      })).then(response => {
        this.orderStates = response.data.data.map(item => {
          item.children = item.childrens
          return item
        })
        // 获取 parent_id为空的所有状态
        this.parentOrderStats = this.orderStates.filter(item => !item.parent_id)

        // 构建树形数据
        this.buildStateTreeData()

        // 如果URL中有state参数，自动设置树形选择器的值
        if (this.state) {
          this.setTreeValueByStateIds(this.state)
        }

        console.log(this.orderStates)
        this.orderstatesloading = false
      }).catch(err => {
        console.log(err)
        this.orderstatesloading = false
        throw err
      })
    },
    buildStateTreeData() {
      // 构建树形结构数据
      this.stateTreeData = this.parentOrderStats.map(item => ({
        id: item.id,
        name: item.name,
        color: item.color,
        children: (item.children || []).map(child => ({
          id: child.id,
          name: child.name,
          color: child.color,
          children: []
        }))
      }))

      // 设置默认展开的键
      this.expandedStateKeys = this.parentOrderStats.map(item => item.id)
    },
    setTreeValueByStateIds(stateIds) {
      if (!stateIds) return

      const ids = stateIds.split(',').filter(Boolean)

      // 等待DOM更新后设置选中状态
      this.$nextTick(() => {
        if (this.$refs.stateTree) {
          this.$refs.stateTree.setCheckedKeys(ids)
          this.updateSelectedStatesFromTree()
        }
      })
    },
    updateSelectedStatesFromTree() {
      if (!this.$refs.stateTree) return

      const checkedNodes = this.$refs.stateTree.getCheckedNodes()
      this.selectedStateNames = checkedNodes.map(node => node.name)
    },
    // 状态分组相关方法
    async loadStateGroups() {
      this.groupsLoading = true
      try {
        const response = await GetStateGroups({ pagesize: 100 })
        this.stateGroups = response.data.data
      } catch (error) {
        console.error('加载状态分组失败:', error)
        this.$message.error('加载状态分组失败')
      } finally {
        this.groupsLoading = false
      }
    },
    async handleApplyGroup(groupId) {
      if (!groupId) {
        // 清空选择
        this.selectedGroupId = null
        this.state = ''
        this.cascaderValue = []
        this.selectedStateNames = []
        if (this.$refs.stateTree) {
          this.$refs.stateTree.setCheckedKeys([])
        }
        this.getList()
        return
      }

      try {
        const response = await ApplyStateGroup(groupId)
        const states = response.data.states

        // 将状态ID转换为逗号分隔的字符串
        this.state = states.join(',')

        // 更新树形选择器的值
        this.setTreeValueByStateIds(this.state)

        // 刷新列表
        this.getList()

        this.$message.success(`已应用分组：${response.data.group_name}`)
      } catch (error) {
        console.error('应用分组失败:', error)
        this.$message.error('应用分组失败')
      }
    },
    handleCloseGroupManager() {
      this.showGroupManager = false
      this.showGroupForm = false
      this.resetGroupForm()
    },
    editGroup(group) {
      this.editingGroupId = group.id
      this.groupForm = {
        name: group.name,
        states: group.states.map(id => {
          const path = this.findStatePath(this.orderStates, id)
          return path || [id]
        }),
        color: group.color,
        description: group.description,
        is_default: group.is_default
      }
      this.showGroupForm = true
    },
    async deleteGroup(group) {
      try {
        await this.$confirm(`确定要删除分组"${group.name}"吗？`, '确认删除', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })

        await DeleteStateGroup(group.id)
        this.$message.success('删除成功')

        // 如果删除的是当前选中的分组，清空选择
        if (this.selectedGroupId === group.id) {
          this.selectedGroupId = null
        }

        // 重新加载分组列表
        this.loadStateGroups()
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除分组失败:', error)
          this.$message.error('删除分组失败')
        }
      }
    },
    async saveGroup() {
      // 验证表单
      try {
        await this.$refs.groupFormRef.validate()
      } catch (error) {
        return
      }

      this.saveLoading = true
      try {
        // 将级联选择器的值转换为状态ID数组
        const states = this.groupForm.states.map(v => {
          return Array.isArray(v) ? v[v.length - 1] : v
        }).filter(Boolean)

        const groupData = {
          name: this.groupForm.name,
          states: states,
          color: this.groupForm.color,
          description: this.groupForm.description,
          is_default: this.groupForm.is_default
        }

        if (this.editingGroupId) {
          await UpdateStateGroup(this.editingGroupId, groupData)
          this.$message.success('更新成功')
        } else {
          await CreateStateGroup(groupData)
          this.$message.success('创建成功')
        }

        this.showGroupForm = false
        this.resetGroupForm()
        this.loadStateGroups()
      } catch (error) {
        console.error('保存分组失败:', error)
        this.$message.error('保存分组失败')
      } finally {
        this.saveLoading = false
      }
    },
    resetGroupForm() {
      this.editingGroupId = null
      this.groupForm = {
        name: '',
        states: [],
        color: '#409EFF',
        description: '',
        is_default: false
      }
      if (this.$refs.groupFormRef) {
        this.$refs.groupFormRef.resetFields()
      }
    }
  }
}
</script>

<style scoped>
.el-tag--dark {
  border-color: #ffffff;
}
.paste-area {
  border: 2px dashed #ccc;
  padding: 20px;
  text-align: center;
}

.el-header, .el-footer {
  background-color: #fff;
  color: #333;
  text-align: left;
  line-height: normal;
}

/* 筛选区域样式 */
.filter-header {
  background-color: #f8f9fa;
  border-bottom: 1px solid #e9ecef;
  padding: 16px 20px;
  height: auto !important;
}

.filter-container {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.filter-row {
  display: flex;
  align-items: center;
  gap: 20px;
  flex-wrap: wrap;
}

.filter-group {
  display: flex;
  align-items: center;
  gap: 8px;
}

.filter-group.flex-1 {
  flex: 1;
  min-width: 300px;
}

.filter-label {
  font-size: 13px;
  color: #606266;
  font-weight: 500;
  white-space: nowrap;
  margin: 0;
  min-width: 60px;
}

.filter-input-group {
  display: flex;
  align-items: center;
  gap: 4px;
}

.filter-actions {
  display: flex;
  gap: 8px;
}

.group-color-indicator {
  display: inline-block;
  width: 12px;
  height: 12px;
  border-radius: 50%;
  margin-right: 6px;
  vertical-align: middle;
}

.group-form-dialog .el-form-item {
  margin-bottom: 20px;
}

.group-table .state-tag {
  margin-right: 4px;
  margin-bottom: 2px;
}

/* 状态树形选择器样式 */
.state-selector-btn {
  text-align: left;
  justify-content: space-between;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  background: white;
  color: #606266;
}

.state-selector-btn:hover {
  border-color: #c0c4cc;
}

.state-selector-btn.is-focus {
  border-color: #409eff;
}

.state-selector-btn .placeholder-text {
  color: #c0c4cc;
}

.state-selector-btn .selected-text {
  color: #606266;
}

.state-tree-container {
  padding: 0;
}

.state-tree-header {
  padding: 12px;
  border-bottom: 1px solid #ebeef5;
}

.quick-groups-section {
  margin-bottom: 12px;
  padding-bottom: 12px;
  border-bottom: 1px solid #f0f0f0;
}

.quick-groups-controls {
  display: flex;
  align-items: center;
  gap: 8px;
}

.quick-groups-controls .groups-select {
  flex: 1;
}

.quick-groups-controls .groups-manage-btn {
  flex-shrink: 0;
}

.state-tree-actions {
  display: flex;
  justify-content: space-between;
}

.state-tree-actions .el-button {
  padding: 0;
  color: #409eff;
  font-size: 12px;
}

.state-tree-actions .el-button:hover {
  color: #66b1ff;
}

.state-tree {
  padding: 12px;
  max-height: 300px;
  overflow-y: auto;
}

.state-tree .el-tree-node__content {
  height: 32px;
  line-height: 32px;
  padding-left: 16px;
}

.state-tree .el-tree-node__content:hover {
  background-color: #f5f7fa;
}

.state-tree .el-tree-node__label {
  font-size: 13px;
  color: #606266;
}

.state-tree .el-checkbox__input.is-checked .el-checkbox__inner {
  background-color: #409eff;
  border-color: #409eff;
}

.state-tree .el-checkbox__input.is-indeterminate .el-checkbox__inner {
  background-color: #409eff;
  border-color: #409eff;
}

.state-tree-node {
  display: flex;
  align-items: center;
  flex: 1;
}

.state-color-indicator {
  display: inline-block;
  width: 8px;
  height: 8px;
  border-radius: 50%;
  margin-right: 6px;
  flex-shrink: 0;
}

.state-name {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

/* 响应式样式 */
@media screen and (max-width: 768px) {
  .filter-header {
    padding: 12px 16px;
  }

  .filter-container {
    gap: 12px;
  }

  .filter-row {
    gap: 12px;
  }

  .filter-group {
    flex-direction: column;
    align-items: flex-start;
    gap: 4px;
    width: 100%;
  }

  .filter-group .el-input {
    width: 100% !important;
  }

  .filter-label {
    font-size: 12px;
    min-width: unset;
  }

  .filter-input-group {
    width: 100%;
  }

  .filter-input-group .el-select {
    flex: 1;
  }

  .filter-actions {
    width: 100%;
    justify-content: flex-end;
  }

  .el-cascader,
  .el-date-picker,
  .state-selector-btn {
    width: 100% !important;
  }

    .state-tree-popover {
    width: 90vw !important;
    max-width: 350px !important;
  }

  .quick-groups-controls {
    flex-direction: column;
    align-items: stretch;
    gap: 8px;
  }

  .quick-groups-controls .groups-select {
    width: 100%;
  }
}

.el-aside {
  background-color: #fff;
  border-left: 1px solid #ebeef5;
  color: #333;
  padding-top: 20px;
  padding-left: 10px;
  line-height: 250px;
}

.el-main {
  background-color: #fff;
  color: #333;
  text-align: center;
}

body > .el-container {
  margin-bottom: 40px;
}

.el-container:nth-child(5) .el-aside,
.el-container:nth-child(6) .el-aside {
  line-height: 260px;
}

.el-container:nth-child(7) .el-aside {
  line-height: 320px;
}

.el-tag + .el-tag {
  margin-left: 10px;
}

.app-container >>> .el-dialog {
  margin-top: 48px !important;
  margin-bottom: 68px;
}

.mt-detail:hover, .svg-icon:hover {
  cursor: pointer;
}

.mt-detail {
  color: #1976d2;
}

.mt-dialog >>> .el-dialog {
  margin: 88px auto !important;
}

.clearfix ::after {
  content: "";
  clear: both
}

.mt-table {
  color: black;
  padding: 20px;
}

.mt-pagination {
  float: right;
  margin-top: 10px;
}

.mt-top {
  margin: 15px 0;
}

.mt-row-btn {
  float: right;
  vertical-align: middle;
  color: white;
}

.mt-btn {
  background-color: rgba(0, 0, 0, 0);
  background-image: none;
  border-radius: 1000px;
  border-bottom-style: solid;
  border-bottom-width: 1px;
  border-collapse: collapse;
  border-image-outset: 0px;
  border-image-repeat: stretch;
  border-image-slice: 100%;
  border-image-source: none;
  border-image-width: 1;
  border-left-style: solid;
  border-left-width: 1px;
  border-right-style: solid;
  border-right-width: 1px;
  border-top-style: solid;
  border-top-width: 1px;
  box-sizing: border-box;
  color: #46be8a;
  cursor: pointer;
  display: block;
  float: right;
  font-family: "Helvetica Neue", Helvetica, Tahoma, Arial, "Microsoft Yahei", "Hiragino Sans GB", "WenQuanYi Micro Hei", sans-serif;
  font-size: 14px;
  font-weight: 400;
  height: 26px;
  hyphens: manual;
  line-height: 14px;
  margin-bottom: 0px;
  margin-right: 10px;
  padding: 5px;
  text-align: center;
  text-decoration-color: rgb(82, 96, 105);
  text-decoration-line: none;
  text-decoration-style: solid;
  text-rendering: optimizeLegibility;
  text-size-adjust: 100%;
  touch-action: manipulation;
  transition-delay: 0s, 0s, 0s, 0s;
  transition-duration: 0.2s, 0.2s, 0.2s, 0.2s;
  transition-property: border, color, width, background-color;
  transition-timing-function: linear, linear, linear, linear;
  user-select: none;
  vertical-align: middle;
  visibility: visible;
  white-space: nowrap;
  background: white;
}

/* 修复linter错误 */
.mt-btn:hover >>> .mt-icon {
  color: #fff;
}

.mt-btn:hover {
  background: #46be8a;
}

.danger:hover {
  background-color: #F56C6C;
}

.danger {
  color: #F56C6C;
}

.default:hover {
  background-color: #62a8ea;
}

.default {
  color: #62a8ea;
}

.edit:hover {
  background-color: #909399;
}

.edit {
  color: #909399;
}

.mt-row-title {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  width: calc(100% - 220px);
  display: inline-block;
  vertical-align: middle;
}

.mt-row-btns {
  float: right;
  margin-right: 10px;
  z-index: 10000;
}

/* 表格行样式优化 */
.el-table :deep(.el-table__row) {
  border-bottom: 2px solid #f5f7fa;
}

.el-table :deep(.el-table__row:hover) {
  background-color: #e8f4fd !important;
}

.el-table :deep(.el-table__row--striped) {
  background-color: #fafafa;
}

.el-table :deep(.el-table__row--striped:hover) {
  background-color: #d4eefc !important;
}

.el-table :deep(.el-table td) {
  padding: 12px 0;
  border-bottom: 1px solid #ebeef5;
}

.el-table :deep(.el-table th) {
  background-color: #f8f9fa;
  color: #606266;
  font-weight: 600;
}

  </style>

<style>
/* 全局表格样式 - 不使用scoped */
.app-container .el-table {
  border: 2px solid #d0d7de !important;
}

.app-container .el-table .el-table__row {
  border-bottom: 2px solid #d0d7de !important;
}

.app-container .el-table .el-table__row:hover > td {
  background-color: #e8f4fd !important;
}

.app-container .el-table .el-table__row--striped {
  background-color: #fafafa !important;
}

.app-container .el-table .el-table__row--striped:hover > td {
  background-color: #d4eefc !important;
}

.app-container .el-table td {
  padding: 12px 0 !important;
  border-bottom: 2px solid #d0d7de !important;
  border-right: 1px solid #d0d7de !important;
}

.app-container .el-table th {
  background-color: #f8f9fa !important;
  color: #606266 !important;
  font-weight: 600 !important;
  border-bottom: 2px solid #d0d7de !important;
  border-right: 1px solid #d0d7de !important;
}

.app-container .el-table--border {
  border: 2px solid #d0d7de !important;
}

.app-container .el-table--border .el-table__cell {
  border-right: 1px solid #d0d7de !important;
}

/* 状态树形选择器全局样式 */
.state-tree-popover {
  padding: 0 !important;
  border-radius: 6px !important;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1) !important;
}

.state-tree-popover .el-popover__title {
  display: none;
}

.state-tree-popover .el-popover__content {
  padding: 0;
}
</style>
